<template>
  <view class="recharge-container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <uni-search-bar
          placeholder="搜索充值金额、套餐名称"
          :clearButton="true"
          :cancelButton="true"
          @confirm="onSearch"
          @input="onSearchInput"
          v-model="searchKeyword"
      />
    </view>

    <!-- 充值金额列表 -->
    <view class="recharge-list" v-if="filteredRecharges.length > 0">
      <uni-list>
        <uni-swipe-action>
          <uni-swipe-action-item
              v-for="(item, index) in filteredRecharges"
              :key="item.id"
              :right-options="swipeOptions"
              @click="onSwipeClick"
          >
            <uni-list-item
                :title="'¥' + item.amount"
                :note="item.packageName"
                :rightText="'赠' + (item.giftType === 'times' ? item.giftValue + '次' : '¥' + item.giftValue)"
                :showArrow="false"
                clickable
                @click="onItemClick(item)"
            >
              <template v-slot:footer>
                <text class="gift-type-text">{{ item.giftType === 'times' ? '赠送次数' : '赠送金额' }}</text>
                <text class="status-text" :class="{ active: item.status === 1 }">
                  {{ item.status === 1 ? '启用中' : '已停用' }}
                </text>
              </template>
            </uni-list-item>
          </uni-swipe-action-item>
        </uni-swipe-action>
      </uni-list>
    </view>

    <!-- 空状态提示 -->
    <view class="empty-state" v-else>
      <uni-icons type="wallet" size="60" color="#ccc" />
      <text class="empty-text">暂无充值套餐</text>
      <text class="empty-subtext">点击下方按钮添加充值套餐</text>
    </view>

    <!-- 状态切换滑块 -->
    <view class="status-slider" v-if="filteredRecharges.length > 0">
      <text class="slider-label">状态筛选：</text>
      <uni-data-checkbox
          v-model="statusFilter"
          :localdata="statusOptions"
          @change="onStatusChange"
      />
    </view>

    <!-- 悬浮管理按钮 -->
    <uni-fab
        :pattern="fabPattern"
        horizontal="right"
        vertical="bottom"
        :content="fabContent"
        @trigger="onFabTrigger"
    />

    <!-- 新增/编辑弹窗 -->
    <uni-popup ref="popup" type="center">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">{{ isEditing ? '编辑充值套餐' : '新增充值套餐' }}</text>
          <uni-icons type="close" size="24" @click="closePopup" />
        </view>

        <view class="form-container">
          <view class="form-item">
            <text class="label">充值金额</text>
            <input class="input" v-model="formData.amount" type="number" placeholder="请输入充值金额" />
          </view>

          <view class="form-item">
            <text class="label">套餐名称</text>
            <input class="input" v-model="formData.packageName" placeholder="请输入套餐名称" />
          </view>

          <view class="form-item">
            <text class="label">赠送类型</text>
            <uni-data-checkbox
                v-model="formData.giftType"
                :localdata="giftTypeOptions"
                @change="onGiftTypeChange"
            />
          </view>

          <view class="form-item">
            <text class="label">赠送值</text>
            <input class="input" v-model="formData.giftValue" type="number" placeholder="请输入赠送值" />
          </view>

          <view class="form-item">
            <text class="label">状态</text>
            <switch
                :checked="formData.status === 1"
                @change="onStatusSwitchChange"
                color="#007AFF"
            />
            <text class="switch-label">{{ formData.status === 1 ? '启用' : '停用' }}</text>
          </view>

          <view class="form-item">
            <text class="label">套餐描述</text>
            <textarea class="textarea" v-model="formData.description" placeholder="请输入套餐描述" />
          </view>
        </view>

        <view class="popup-actions">
          <button class="btn-cancel" @click="closePopup">取消</button>
          <button class="btn-confirm" @click="saveRecharge">保存</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  data() {
    return {
      searchKeyword: '',
      statusFilter: 2, // 2表示全部
      rechargeList: [
        {
          id: 1,
          amount: '100.00',
          packageName: '基础套餐',
          giftType: 'times',
          giftValue: '5',
          description: '充值100元赠送5次服务',
          status: 1,
          createTime: '2024-01-15'
        },
        {
          id: 2,
          amount: '200.00',
          packageName: '标准套餐',
          giftType: 'amount',
          giftValue: '20.00',
          description: '充值200元赠送20元',
          status: 1,
          createTime: '2024-01-16'
        },
        {
          id: 3,
          amount: '500.00',
          packageName: '豪华套餐',
          giftType: 'times',
          giftValue: '30',
          description: '充值500元赠送30次服务',
          status: 0,
          createTime: '2024-01-17'
        }
      ],
      statusOptions: [
        { value: 2, text: '全部' },
        { value: 1, text: '启用中' },
        { value: 0, text: '已停用' }
      ],
      giftTypeOptions: [
        { value: 'times', text: '赠送次数' },
        { value: 'amount', text: '赠送金额' }
      ],
      swipeOptions: [
        {
          text: '编辑',
          style: {
            backgroundColor: '#007AFF'
          }
        },
        {
          text: '删除',
          style: {
            backgroundColor: '#DD524D'
          }
        }
      ],
      fabPattern: {
        color: '#fff',
        backgroundColor: '#007AFF',
        selectedColor: '#007AFF',
        buttonColor: '#007AFF'
      },
      fabContent: [
        {
          text: '新增套餐',
          iconPath: '/static/icons/add.png',
          selectedIconPath: '/static/icons/add-active.png'
        },
        {
          text: '批量操作',
          iconPath: '/static/icons/batch.png',
          selectedIconPath: '/static/icons/batch-active.png'
        }
      ],
      formData: {
        id: null,
        amount: '',
        packageName: '',
        giftType: 'times',
        giftValue: '',
        description: '',
        status: 1
      },
      isEditing: false,
      currentEditIndex: -1
    }
  },
  computed: {
    filteredRecharges() {
      let list = this.rechargeList

      // 状态筛选
      if (this.statusFilter !== 2) {
        list = list.filter(item => item.status === this.statusFilter)
      }

      // 关键词搜索
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase()
        list = list.filter(item =>
            item.amount.toLowerCase().includes(keyword) ||
            item.packageName.toLowerCase().includes(keyword) ||
            item.description.toLowerCase().includes(keyword)
        )
      }

      return list
    }
  },
  methods: {
    onSearch(e) {
      console.log('搜索关键词:', e.value)
    },
    onSearchInput(e) {
      this.searchKeyword = e
    },
    onStatusChange(e) {
      this.statusFilter = e.detail.value
    },
    onSwipeClick(e) {
      const { index, content, position } = e
      if (position === 'right') {
        if (content.text === '编辑') {
          this.editRecharge(index)
        } else if (content.text === '删除') {
          this.deleteRecharge(index)
        }
      }
    },
    onItemClick(item) {
      uni.showToast({
        title: `查看套餐: ${item.packageName}`,
        icon: 'none'
      })
    },
    onFabTrigger(e) {
      const { index, item } = e
      switch (index) {
        case 0: // 新增套餐
          this.showAddPopup()
          break
        case 1: // 批量操作
          this.batchOperation()
          break
      }
    },
    onGiftTypeChange(e) {
      this.formData.giftType = e.detail.value
    },
    onStatusSwitchChange(e) {
      this.formData.status = e.detail.value ? 1 : 0
    },
    showAddPopup() {
      this.resetForm()
      this.isEditing = false
      this.$refs.popup.open()
    },
    editRecharge(index) {
      const item = this.rechargeList[index]
      this.formData = { ...item }
      this.isEditing = true
      this.currentEditIndex = index
      this.$refs.popup.open()
    },
    deleteRecharge(index) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除这个充值套餐吗？',
        success: (res) => {
          if (res.confirm) {
            this.rechargeList.splice(index, 1)
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
          }
        }
      })
    },
    saveRecharge() {
      if (!this.formData.amount || !this.formData.packageName || !this.formData.giftValue) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        })
        return
      }

      if (this.isEditing) {
        // 更新套餐
        this.rechargeList[this.currentEditIndex] = { ...this.formData }
        uni.showToast({
          title: '更新成功',
          icon: 'success'
        })
      } else {
        // 新增套餐
        const newRecharge = {
          ...this.formData,
          id: Date.now(),
          createTime: new Date().toISOString().split('T')[0]
        }
        this.rechargeList.unshift(newRecharge)
        uni.showToast({
          title: '添加成功',
          icon: 'success'
        })
      }

      this.closePopup()
    },
    batchOperation() {
      uni.showActionSheet({
        itemList: ['批量启用', '批量停用', '批量删除'],
        success: (res) => {
          const tapIndex = res.tapIndex
          switch (tapIndex) {
            case 0: // 批量启用
              this.batchUpdateStatus(1)
              break
            case 1: // 批量停用
              this.batchUpdateStatus(0)
              break
            case 2: // 批量删除
              this.batchDelete()
              break
          }
        }
      })
    },
    batchUpdateStatus(status) {
      const selectedCount = this.filteredRecharges.length
      if (selectedCount === 0) {
        uni.showToast({
          title: '没有可操作的项目',
          icon: 'none'
        })
        return
      }

      uni.showModal({
        title: '确认操作',
        content: `确定要${status === 1 ? '启用' : '停用'} ${selectedCount} 个套餐吗？`,
        success: (res) => {
          if (res.confirm) {
            this.filteredRecharges.forEach(item => {
              item.status = status
            })
            uni.showToast({
              title: '操作成功',
              icon: 'success'
            })
          }
        }
      })
    },
    batchDelete() {
      const selectedCount = this.filteredRecharges.length
      if (selectedCount === 0) {
        uni.showToast({
          title: '没有可删除的项目',
          icon: 'none'
        })
        return
      }

      uni.showModal({
        title: '确认删除',
        content: `确定要删除 ${selectedCount} 个套餐吗？此操作不可恢复。`,
        success: (res) => {
          if (res.confirm) {
            const idsToDelete = this.filteredRecharges.map(item => item.id)
            this.rechargeList = this.rechargeList.filter(item => !idsToDelete.includes(item.id))
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            })
          }
        }
      })
    },
    resetForm() {
      this.formData = {
        id: null,
        amount: '',
        packageName: '',
        giftType: 'times',
        giftValue: '',
        description: '',
        status: 1
      }
    },
    closePopup() {
      this.$refs.popup.close()
    }
  }
}
</script>

<style scoped lang="scss">
.recharge-container {
  padding-bottom: 100px;
  min-height: 100vh;
  background-color: #f8f8f8;
}

.search-bar {
  position: sticky;
  top: 0;
  z-index: 10;
  background: #fff;
  padding: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.recharge-list {
  margin-top: 10px;
}

.status-slider {
  display: flex;
  align-items: center;
  padding: 15px;
  background: #fff;
  margin: 10px 0;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.slider-label {
  font-size: 14px;
  color: #666;
  margin-right: 10px;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100px 20px;
  text-align: center;
}

.empty-text {
  font-size: 16px;
  color: #999;
  margin-top: 20px;
}

.empty-subtext {
  font-size: 14px;
  color: #ccc;
  margin-top: 10px;
}

.gift-type-text {
  font-size: 12px;
  color: #666;
  margin-right: 8px;
}

.status-text {
  font-size: 12px;
  color: #999;

  &.active {
    color: #07C160;
    font-weight: bold;
  }
}

.popup-content {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  width: 80vw;
  max-width: 400px;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.popup-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.form-item {
  margin-bottom: 15px;
}

.label {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.input, .textarea {
  width: 90%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  background: #fff;
}

.textarea {
  height: 80px;
  resize: none;
}

.switch-label {
  font-size: 14px;
  color: #666;
  margin-left: 10px;
}

.popup-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.btn-cancel, .btn-confirm {
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 14px;
  border: none;
}

.btn-cancel {
  background: #f0f0f0;
  color: #666;
}

.btn-confirm {
  background: #007AFF;
  color: #fff;
}
</style>